<template>
  <n-scrollbar @scroll="handleScroll" ref="aiMessageListRef">
    <div v-for="(item,index) in list" :key="index" class="px-5 py-3">
      <div :class="item.role==='user'?'flex flex-col items-end':''">
        <AiMessageItem @handleRemove="handleRemove"
                       @handleReload="handleReload"
                       :item="item" :show-operate-button="index!==0"
                       :key="index"></AiMessageItem>
      </div>
    </div>
  </n-scrollbar>

</template>

<script setup lang="ts">

import {nextTick, PropType, ref, watch} from "vue";
import AiMessageItem from "@/components/pc/item/AiMessageItem.vue";
import {useAiStore} from "@/store";

const props = defineProps({
  list: {
    type: Array as PropType<IAiMessage[]>,
    default: () => []
  }
})
const aiMessageListRef = ref()
const isInBottom = ref(false)
const aiStore = useAiStore()

watch(props, () => {
  if (isInBottom.value) {
    scrollToBottom()
  }
})

const handleScroll = (e: any) => {
  isInBottom.value = e.target.scrollHeight - e.target.scrollTop <= e.target.clientHeight + 50;
}
const scrollToBottom = () => {
  nextTick(() => {
    aiMessageListRef.value.scrollBy({top: 999999})
  })
}

const handleRemove = (item: IAiMessage) => {
  props.list?.findIndex((i, index) => {
    if (i === item) {
      props.list?.splice(index, 1)
    }
  })
}
const handleReload = (item: IAiMessage) => {
  props.list?.findIndex((i, index) => {
    if (i === item) {
      let idx = index + 1
      if (idx % 2) {
        let pre = props.list?.[index - 1]
        props.list?.splice(index - 1, 2)
        aiStore.sendMessage(pre?.content)
      } else {
        props.list?.splice(index, 2)
        aiStore.sendMessage(item?.content)
      }
    }
  })
}
const doScrollToBottom = () => {
  scrollToBottom()
}

defineExpose({
  doScrollToBottom
})

</script>

<style scoped>
:deep(.md-editor-preview-wrapper) {
  padding: 0 5px;
}

:deep(.md-editor-previewOnly) {
  border-radius: 5px;
}
</style>